import React, { useState, useEffect } from "react";
import {
  Card,
  Form,
  Input,
  Button,
  message,
  Avatar,
  Typography,
  Space,
  List,
  Divider,
  Upload,
} from "antd";
import {
  UserOutlined,
  EditOutlined,
  SaveOutlined,
  CloseOutlined,
  CrownOutlined,
  CameraOutlined,
  HomeOutlined,
} from "@ant-design/icons";
import request from "../../utils/request";
import { useNavigate } from "react-router-dom";
import "./index.less";
import useAuthStore from "../../stores/authStore";
import ImgCrop from "antd-img-crop"; // 需要先安装: npm install antd-img-crop

const { Title, Text } = Typography;

const Profile = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [isEditing, setIsEditing] = useState(false);
  const [profile, setProfile] = useState(null);
  const navigate = useNavigate();
  const { user, updateUserInfo } = useAuthStore();

  // 获取个人信息
  const fetchProfile = async () => {
    try {
      if (!user?.id) return;
      const res = await request.get(`/api/admin/profile/${user.id}`);
      if (res.code === 0) {
        setProfile(res.data);
        form.setFieldsValue(res.data);
      }
    } catch (error) {
      message.error("获取个人信息失败");
    }
  };

  useEffect(() => {
    fetchProfile();
  }, []);

  // 修改提交处理函数
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      const teacherId = 1;

      const updateData = {
        ...values,
        avatar: profile?.avatar,
        title: profile?.title,
      };

      // 使用 store 的更新方法
      const updatedUser = await updateUserInfo(teacherId, updateData);
      if (updatedUser) {
        setProfile(updatedUser);
        setIsEditing(false);
        message.success("个人信息更新成功");
      }
    } catch (error) {
      message.error("更新失败");
    } finally {
      setLoading(false);
    }
  };

  // 修改头像上传处理函数
  const handleAvatarChange = async (info) => {
    if (info.file.status === 'uploading') {
      return;
    }
    if (info.file.status === 'done') {
      const { response } = info.file;
      if (response.code === 0) {
        const timestamp = Date.now();
        const newProfile = {
          ...profile,
          avatar: response.data.url,  // 存储原始URL
          avatarTimestamp: timestamp  // 添加时间戳字段
        };
        setProfile(newProfile);
        // 更新全局状态
        updateUserInfo(1, newProfile);
        message.success('头像更新成功');
      } else {
        message.error('头像更新失败');
      }
    } else if (info.file.status === 'error') {
      message.error('头像上传失败');
    }
  };

  // 渲染头像与基本信息区
  const renderHeader = () => (
    <div className="profile-header">
      <div className="avatar-wrapper">
        <Avatar
          size={120}
          icon={<UserOutlined />}
          src={profile?.avatar ? `${profile.avatar}?t=${profile.avatarTimestamp || Date.now()}` : null}
        />
        <ImgCrop
          rotationSlider
          quality={1}
          modalTitle="裁剪头像"
          modalOk="确认"
          modalCancel="取消"
          aspect={1} // 固定裁剪比例为1:1
        >
          <Upload
            name="avatar"
            action={`/api/teacher/upload/avatar/${user?.id}`} // 使用动态ID
            showUploadList={false}
            onChange={handleAvatarChange}
            accept="image/*"
            maxSize={5 * 1024 * 1024}
          >
            <div className="avatar-edit-button">
              <CameraOutlined />
              <div className="avatar-tip">建议尺寸 200x200</div>
            </div>
          </Upload>
        </ImgCrop>
      </div>
      <div className="user-info">
        <Title level={3}>{profile?.name}</Title>
        <Space align="center" className="member-status">
          <CrownOutlined />
          <Text>{profile?.title || "高级教师"}</Text>
        </Space>
      </div>
    </div>
  );

  // 渲染个人资料展示区
  const renderProfile = () => (
    <div className="profile-details">
      <Card
        title="个人资料"
        extra={
          !isEditing && (
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => setIsEditing(true)}
            >
              编辑资料
            </Button>
          )
        }
      >
        {isEditing ? (
          <Form form={form} layout="vertical" onFinish={handleSubmit}>
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: "请输入用户名" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: "请输入姓名" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="邮箱"
              name="email"
              rules={[
                { required: true, message: "请输入邮箱" },
                { type: "email", message: "请输入有效的邮箱地址" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="手机号"
              name="phone"
              rules={[
                { required: true, message: "请输入手机号" },
                { pattern: /^1[3-9]\d{9}$/, message: "请输入有效的手机号" },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item label="个人简介" name="description">
              <Input.TextArea rows={4} />
            </Form.Item>

            <Form.Item className="form-buttons">
              <Space>
                <Button
                  onClick={() => setIsEditing(false)}
                  icon={<CloseOutlined />}
                >
                  取消
                </Button>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  icon={<SaveOutlined />}
                >
                  保存
                </Button>
              </Space>
            </Form.Item>
          </Form>
        ) : (
          <List split={true} className="info-list">
            <List.Item>
              <Text type="secondary">用户名</Text>
              <Text>{profile?.username}</Text>
            </List.Item>
            <List.Item>
              <Text type="secondary">姓名</Text>
              <Text>{profile?.name}</Text>
            </List.Item>
            <List.Item>
              <Text type="secondary">邮箱</Text>
              <Text>{profile?.email}</Text>
            </List.Item>
            <List.Item>
              <Text type="secondary">手机号</Text>
              <Text>{profile?.phone}</Text>
            </List.Item>
            <List.Item>
              <Text type="secondary">个人简介</Text>
              <Text>{profile?.description || "暂无简介"}</Text>
            </List.Item>
          </List>
        )}
      </Card>
    </div>
  );

  // 添加返回首页按钮
  const renderPageHeader = () => (
    <div className="page-header">
      <Button type="link" icon={<HomeOutlined />} onClick={() => navigate("/")}>
        返回首页
      </Button>
    </div>
  );

  return (
    <div className="profile-page">
      {renderPageHeader()}
      {renderHeader()}
      <Divider />
      {renderProfile()}
    </div>
  );
};

export default Profile;
